﻿using System;

namespace QuickDev.SSO
{
    /// <summary>
    /// <para>SsoTicket</para>
    /// </summary>
    [Serializable]
    public class SsoTicket
    {
        #region Private Fields
        private int _userId;
        private string _userName;
        private string _roles;
        private DateTime _timeStamp;
        private int _expireDuration;
        #endregion

        #region Public Properties

        /// <summary>
        /// UserId
        /// </summary>
        public int UserId
        {
            get { return _userId; }
            set { _userId = value; }
        }

        /// <summary>
        /// UserName
        /// </summary>
        public string UserName
        {
            get { return _userName; }
            set { _userName = value; }
        }

        /// <summary>
        /// Roles
        /// </summary>
        public string Roles
        {
            get { return _roles; }
            set { _roles = value; }
        }

        /// <summary>
        /// TimeStamp
        /// </summary>
        public DateTime TimeStamp
        {
            get { return _timeStamp; }
            set { _timeStamp = value; }
        }

        /// <summary>
        /// ExpireDuration
        /// </summary>
        public int ExpireDuration
        {
            get { return _expireDuration; }
            set { _expireDuration = value; }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Encode
        /// </summary>
        /// <returns>SsoCipher.EncryptVector</returns>
        public string Encode()
        {
            return SsoCipher.EncryptVector(
                _userId.ToString() ,
                _userName ,
                _roles ,
                _timeStamp == default( DateTime ) ? null : _timeStamp.ToString() ,
                _expireDuration.ToString() );
        }

        /// <summary>
        /// TryParse
        /// </summary>
        /// <param name="text">text</param>
        /// <param name="ticket">ticket</param>
        /// <returns>bool successful</returns>
        public static bool TryParse( string text , out SsoTicket ticket )
        {
            ticket = null;
            string[] vector;
            if ( !SsoCipher.TryParseVector( text , out vector ) )
                return false;
            if ( vector.Length != 5 )
                return false;
            ticket = new SsoTicket();
            ticket.UserId = Convert.ToInt32( vector[0] );
            ticket.UserName = vector[1];
            ticket.Roles = vector[2];
            ticket.TimeStamp = Convert.ToDateTime( vector[3] );
            ticket.ExpireDuration = Convert.ToInt32( vector[4] );
            return true;
        }
        #endregion
    }
}